<template>
  <div class="my-color-picker">
    <div style="min-width: 292px; height: 195px; position: relative;">
      <div style="inset: 0px; position: absolute;">
        <div class="color-picker-editor">
          <div class="flex-item">
            <div class="hex-wrap">
              <span class="mr-5">#</span>
              <div class="hex"><input v-model="hexVal"
                  @blur="hexBlur"
                  type="text" /></div>
            </div>
            <div class="rgbv"><input @blur="rbgBlur(rgb[0])"
                v-model="rgb[0]"
                type="text" /></div>
            <div class="rgbv"><input @blur="rbgBlur(rgb[1])"
                v-model="rgb[1]"
                type="text" /></div>
            <div class="rgbv"><input @blur="rbgBlur(rgb[2])"
                v-model="rgb[2]"
                type="text" /></div>
          </div>
          <div class="flex-item">
            <div class="hex-wrap">HEX</div>
            <div class="rgbv">R</div>
            <div class="rgbv">G</div>
            <div class="rgbv">B</div>
          </div>
        </div>
        <div style="position: absolute; left: 0px; right: 0px; top: 50px; height: 38px;">
          <div class="bi-color-picker bi-border-bottom bi-border-right "
            style="height: 34px; left: 10px; right: 10px; top: 5px; position: absolute;">
            <div class="bi-basic-button cursor-pointer bi-border-top bi-border-left"
              v-for="(item, index) in selectedList"
              :key="index"
              :style="item"
              @click="selectedClick(item, index)">
              <div class="bi-abs"
                style="inset: -1px; position: absolute">
                <div :class="{'selected-button-mask': selectedActive===index}"
                  style="inset: 0; position: absolute;z-index: 10"></div>
              </div>

            </div>
          </div>
        </div>
        <div style="position: absolute; inset: 88px 0px 24px;">
          <div class="bi-color-picker"
            style="inset: 5px 10px 10px; position: absolute;">
            <div class="bi-basic-button cursor-pointer bi-border-top bi-border-left"
              v-for="(item, index) in list"
              :key="index"
              :style="item"
              @click="btnClick(item, index)">
              <div :class="{'item-button-mask': listActive===index}"
                style="inset: 0; position: absolute;;z-index: 10"></div>
            </div>
          </div>
        </div>
        <div class="bi-border-top"
          tabindex="-1"
          style="position: absolute; left: 0px; right: 0px; bottom: 0px; height: 24px;">
          <div class="bi-basic-button"
            style="height: 24px; line-height: 24px; padding-left: 10px; white-space: pre; text-overflow: ellipsis; position: relative;">
            <div class="more-input">
              <input class="cursor-pointer"
                @change="colorPickerChange"
                v-model="colorPicker"
                type="color"
                name="favcolor">
            </div>
            <div class="more">
              <span class="cursor-pointer">更多...</span>
            </div>

          </div>
        </div>
      </div>
    </div>
    <transition name="el-fade-in-linear">
      <div v-if="hexTips.show"
        class="left-tips">{{hexTips.value}}</div>
    </transition>

    <transition name="el-fade-in-linear">
      <div v-if="rbgTips.show"
        class="right-tips">{{rbgTips.value}}</div>
    </transition>
  </div>
</template>

<script>
  import { colorList } from './color.js';
  export default {
    props: {
      initColor: {
        type: String,
        default: ''
      }
    },
    data() {
      return {
        selectedList: [
          {
            backgroundColor: 'rgb(255, 255, 255)',
            position: 'absolute',
            inset: '0% 87.5% 0% 0%'
          },
          {
            backgroundColor: 'rgb(195, 216, 37)',
            position: 'absolute',
            inset: '0% 75% 0% 12.5%'
          },
          {
            backgroundColor: 'rgb(224, 235, 175)',
            position: 'absolute',
            inset: '0% 62.5% 0% 25%'
          },
          {
            backgroundColor: 'rgb(216, 230, 152)',
            position: 'absolute',
            inset: '0% 50% 0% 37.5%'
          },
          {
            backgroundColor: 'rgb(245, 229, 107)',
            position: 'absolute',
            inset: '0% 37.5% 0% 50%'
          },
          {
            backgroundColor: 'rgb(255, 193, 125)',
            position: 'absolute',
            inset: '0% 25% 0% 62.5%'
          },
          {
            backgroundColor: 'rgb(255, 158, 154)',
            position: 'absolute',
            inset: '0% 12.5% 0% 75%'
          },
          {
            backgroundColor: 'rgb(216, 181, 166)',
            position: 'absolute',
            inset: '0% 0% 0% 87.5%'
          }
        ],
        list: colorList,
        listActive: -1,
        selectedActive: -1,
        hexVal: '',
        rgb: ['', '', ''],
        colorPicker: '#000000',
        rbgTips: {
          show: false,
          value: '请输入0-255的数字'
        },
        hexTips: {
          show: false,
          value: '请输入正确的16进制数'
        },
        timer1: null,
        timer2: null
      };
    },
    watch: {
      initColor: {
        handler(val) {
          if (val) {
            this.initColorVal(val);
          }
        },
        immediate: true
      }
    },
    methods: {
      emitChange() {
        let rgb = 'rgb(' + this.rgb.join(',') + ')';
        this.$emit('colorChange', rgb);
      },
      initColorVal(rgb) {
        this.hexVal = this.rgbToHex(rgb);
        this.rgb = rgb
          .replace(/rgb?\(/, '')
          .replace(/\)/, '')
          .replace(/[\s+]/g, '')
          .split(',');
        this.selectedActive = 0;
        this.selectedList[0].backgroundColor = rgb;
      },
      // 输入参数格式 如： 'rgba(255,232,186,0.4)'); 输出格式 如："f5faf3"
      rgbaToHex(color) {
        let values = color
          .replace(/rgba?\(/, '')
          .replace(/\)/, '')
          .replace(/[\s+]/g, '')
          .split(',');
        let a = parseFloat(values[3] || 1),
          r = Math.floor(a * parseInt(values[0]) + (1 - a) * 255),
          g = Math.floor(a * parseInt(values[1]) + (1 - a) * 255),
          b = Math.floor(a * parseInt(values[2]) + (1 - a) * 255);
        return ('0' + r.toString(16)).slice(-2) + ('0' + g.toString(16)).slice(-2) + ('0' + b.toString(16)).slice(-2);
      },
      // 输入参数格式 如： '#F30A09'; 输出格式 如：(255,10,9)
      hexToRgb(str) {
        let res = [];
        str = str.slice(1, str.length - 1);
        for (let i = 0; i < str.length; i = i + 2) {
          res.push(Number('0x' + str.substr(i, 2)));
        }
        return ['rgb(' + res.join(',') + ')', res];
      },
      // 输入参数格式 如：'rgb(255,10,9)';  输出格式 如： 'F30A09'
      rgbToHex(str) {
        let res = '';
        str = str.slice(4, str.length - 1);
        let arr = str.split(','); // 里面的元素是字符串格式的

        for (let i = 0; i < arr.length; i++) {
          let item = Number(arr[i]).toString(16).toUpperCase();
          if (item.length == 1) {
            item = '0' + item;
          }
          res = res + item;
        }
        return res;
      },
      selectedClick(item, i) {
        this.selectedActive = i;
        this.setSelectColor(item);
        this.emitChange();
      },
      btnClick(item, i) {
        this.listActive = i;
        this.selectedActive = 0;
        this.setSelectColor(item);
        this.emitChange();
      },
      setSelectColor(item) {
        let rgb = item.backgroundColor;
        this.selectedList[0].backgroundColor = rgb;
        this.hexVal = this.rgbToHex(rgb);
        this.rgb = rgb
          .replace(/rgba?\(/, '')
          .replace(/\)/, '')
          .replace(/[\s+]/g, '')
          .split(',');
      },
      hexBlur() {
        let reg = /[0-9A-Fa-f]{6}/;
        if (reg.test(this.hexVal) && this.hexVal.length === 6) {
          let arr = this.hexToRgb('#' + this.hexVal);
          this.rgb = arr[1];
          this.hexTips.show = false;
          this.timer1 = null;
        } else {
          this.hexTips.show = true;
          this.setTipsTimeout1();
        }
        this.emitChange();
      },
      rbgBlur(val) {
        let reg = /^(([0-9])|(1[0-9][0-9])|(2[0-4][0-9])|(25[0-5]))/;
        let bool = reg.test(val);
        if (bool) {
          this.rbgTips.show = false;
          this.timer2 = null;
        } else {
          this.rbgTips.show = true;
          this.setTipsTimeout2();
        }
        let bool2 = this.rgb.every((item) => Boolean(item));
        if (bool2) {
          let rgb = 'rgb(' + this.rgb.join(',') + ')';
          this.hexVal = this.rgbToHex(rgb);
        }
        this.emitChange();
      },
      colorPickerChange() {
        let arr = this.hexToRgb(this.colorPicker);
        this.rgb = arr[1];
        this.hexVal = this.colorPicker.substr(1);
        this.selectedActive = 0;
        this.listActive = -1;
        this.selectedList[0].backgroundColor = arr[0];
        this.emitChange();
      },
      setTipsTimeout2() {
        this.timer2 = setTimeout(() => {
          if (this.rbgTips.show) {
            this.rbgTips.show = !this.rbgTips.show;
          }
        }, 1500);
      },
      setTipsTimeout1() {
        this.timer1 = setTimeout(() => {
          if (this.hexTips.show) {
            this.hexTips.show = !this.hexTips.show;
          }
        }, 1500);
      }
    }
  };
</script>

<style lang="scss" scoped>
  .my-color-picker {
    position: relative;
    margin-top: 5px;
    padding-top: 15px;
    .left-tips {
      position: absolute;
      font-size: 12px;
      left: 0;
      top: 0;
      color: red;
    }
    .right-tips {
      position: absolute;
      font-size: 12px;
      right: 0;
      top: 0;
      color: red;
    }

    .flex-item {
      display: flex;
      justify-content: space-between;
      margin-top: 5px;
      font-size: 12px;
      .hex-wrap {
        width: 90px;
        text-align: center;
      }
      .hex {
        position: relative;
        display: inline-block;
        width: 68px;
        height: 22px;
        margin-right: 5px;
        text-align: center;
      }
      .rgbv {
        position: relative;
        width: 30px;
        height: 22px;
        margin-right: 5px;
        text-align: center;
      }
      input[type='text'] {
        width: 100%;
        height: 100%;
        border: 1px solid #e8eaed;
        color: #333;
        font-size: 12px;
      }
      input[type='text']:focus {
        outline: none;
        border-color: $--primary-color;
        background-color: #fff;
      }
      input[type='text']::selection {
        background: transparent;
        background-color: #fff;
      }
      input[type='text']::-moz-selection {
        background: transparent;
        background-color: #fff;
      }
    }
    .cursor-pointer {
      cursor: pointer;
    }
    .bi-border-left {
      border-left: 1px solid #eee;
    }
    .bi-border-top {
      border-top: 1px solid #eee;
    }
    .selected-button-mask {
      border: 1px solid #000;
    }
    .item-button-mask {
      border: 1px solid #000;
      transform: scale(1.1);
    }
    .more-input {
      width: 100%;
      position: absolute;
      z-index: 5;
      text-align: center;
      opacity: 0;
    }
    .more {
      width: 100%;
      position: absolute;
      z-index: 2;
      text-align: center;
    }
  }
</style>
